<template>
  <div class="project-list-container">
    <div class="header-actions">
      <div class="left">
        <n-button quaternary circle @click="goBack">
          <template #icon><n-icon><ArrowBackOutline /></n-icon></template>
        </n-button>
        <h1>我的项目</h1>
      </div>
      <div class="right">
        <n-button type="primary" @click="createNewProject">
          <template #icon><n-icon><AddOutline /></n-icon></template>
          新建项目
        </n-button>
        <n-button @click="importProject">
          <template #icon><n-icon><DownloadOutline /></n-icon></template>
          导入项目
        </n-button>
      </div>
    </div>
    
    <n-tabs 
      type="line" 
      v-model:value="activeTab"
      class="custom-tabs"
      size="large"
    >
      <n-tab-pane name="all" tab="全部项目">
        <div class="filter-bar">
          <n-input-group>
            <n-input v-model:value="searchText" placeholder="搜索项目" clearable>
              <template #prefix>
                <n-icon><SearchOutline /></n-icon>
              </template>
            </n-input>
            <n-select
              v-model:value="sortBy"
              :options="sortOptions"
              style="width: 140px"
            />
          </n-input-group>
        </div>
        
        <div class="projects-grid" v-if="filteredProjects.length > 0">
          <n-card
            v-for="project in filteredProjects"
            :key="project.id"
            class="project-card"
            :hoverable="true"
            @click="openProject(project)"
          >
            <template #cover>
              <div class="project-thumbnail">
                <img :src="project.thumbnail || defaultThumbnail" :alt="project.name">
              </div>
            </template>
            <template #header>
              <div class="project-header">
                <div class="project-name">{{ project.name }}</div>
                <n-dropdown
                  trigger="click"
                  :options="projectActions"
                  @select="handleProjectAction($event, project)"
                  placement="bottom-end"
                  @click.stop
                >
                  <n-button quaternary circle size="small">
                    <template #icon><n-icon><EllipsisHorizontal /></n-icon></template>
                  </n-button>
                </n-dropdown>
              </div>
            </template>
            <div class="project-info">
              <div class="info-row">
                <span class="label">创建时间:</span>
                <span class="value">{{ formatDate(project.createdAt) }}</span>
              </div>
              <div class="info-row">
                <span class="label">修改时间:</span>
                <span class="value">{{ formatDate(project.updatedAt) }}</span>
              </div>
              <div class="info-row">
                <span class="label">时长:</span>
                <span class="value">{{ formatDuration(project.duration) }}</span>
              </div>
            </div>
          </n-card>
        </div>
        
        <n-empty
          v-else
          description="暂无项目"
        >
          <template #extra>
            <n-button @click="createNewProject">创建新项目</n-button>
          </template>
        </n-empty>
      </n-tab-pane>
      
      <n-tab-pane name="templates" tab="项目模板">
        <div class="templates-grid" v-if="templates.length > 0">
          <n-card
            v-for="template in templates"
            :key="template.id"
            class="template-card"
            :hoverable="true"
            @click="useTemplate(template)"
          >
            <template #cover>
              <div class="template-thumbnail">
                <img :src="template.thumbnail" :alt="template.name">
              </div>
            </template>
            <template #header>
              <div class="template-name">{{ template.name }}</div>
            </template>
            <div class="template-info">
              <div class="info-row">
                <span class="label">类型:</span>
                <span class="value">{{ template.category }}</span>
              </div>
              <div class="template-description">
                {{ template.description }}
              </div>
            </div>
            <template #footer>
              <n-button block @click.stop="useTemplate(template)">
                使用此模板
              </n-button>
            </template>
          </n-card>
        </div>
        
        <n-empty
          v-else
          description="暂无模板"
        />
      </n-tab-pane>
      
      <n-tab-pane name="recent" tab="最近打开">
        <n-list v-if="recentProjects.length > 0">
          <n-list-item v-for="project in recentProjects" :key="project.id">
            <n-thing
              :title="project.name"
              :description="project.description || '无描述'"
            >
              <template #avatar>
                <div class="project-avatar">
                  <img :src="project.thumbnail || defaultThumbnail" :alt="project.name">
                </div>
              </template>
              <template #header-extra>
                <n-space>
                  <n-button size="small" @click="openProject(project)">
                    打开
                  </n-button>
                </n-space>
              </template>
              <template #default>
                <div class="project-meta">
                  <span>最后打开: {{ formatDate(project.lastOpenedAt) }}</span>
                  <span>时长: {{ formatDuration(project.duration) }}</span>
                </div>
              </template>
            </n-thing>
          </n-list-item>
        </n-list>
        
        <n-empty
          v-else
          description="暂无最近打开的项目"
        />
      </n-tab-pane>
    </n-tabs>
    
    <!-- 新建项目对话框 -->
    <n-modal
      v-model:show="showNewProjectModal"
      preset="dialog"
      title="新建项目"
      positive-text="创建"
      negative-text="取消"
      @positive-click="handleCreateProject"
      @negative-click="cancelCreateProject"
    >
      <n-form
        ref="formRef"
        :model="newProjectForm"
        :rules="formRules"
        label-placement="left"
        label-width="80"
        require-mark-placement="right-hanging"
      >
        <n-form-item label="项目名称" path="name">
          <n-input v-model:value="newProjectForm.name" placeholder="请输入项目名称" />
        </n-form-item>
        
        <n-form-item label="项目描述" path="description">
          <n-input
            v-model:value="newProjectForm.description"
            type="textarea"
            placeholder="请输入项目描述"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </n-form-item>
        
        <n-form-item label="分辨率" path="resolution">
          <n-select
            v-model:value="newProjectForm.resolution"
            :options="resolutionOptions"
            placeholder="请选择分辨率"
          />
        </n-form-item>
        
        <n-form-item label="帧率" path="frameRate">
          <n-select
            v-model:value="newProjectForm.frameRate"
            :options="frameRateOptions"
            placeholder="请选择帧率"
          />
        </n-form-item>
      </n-form>
    </n-modal>
    
    <!-- 导入项目对话框 -->
    <n-modal
      v-model:show="showImportModal"
      preset="dialog"
      title="导入项目"
      positive-text="导入"
      negative-text="取消"
      @positive-click="handleImportProject"
      @negative-click="cancelImportProject"
    >
      <n-upload
        action="#"
        :default-upload="false"
        :on-before-upload="beforeUpload"
        accept=".spf"
      >
        <n-upload-dragger>
          <div style="padding: 20px">
            <n-icon size="48" depth="3">
              <CloudUploadOutline />
            </n-icon>
            <div style="margin-top: 12px">点击或拖拽文件到此处上传</div>
            <div style="margin-top: 8px">
              <n-text depth="3">支持 .spf 格式的皮影快闪项目文件</n-text>
            </div>
          </div>
        </n-upload-dragger>
      </n-upload>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
  NButton,
  NIcon,
  NTabs,
  NTabPane,
  NCard,
  NEmpty,
  NList,
  NListItem,
  NThing,
  NSpace,
  NModal,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NInputGroup,
  NDropdown,
  NUpload,
  NUploadDragger,
  NText,
  FormInst
} from 'naive-ui'
import {
  AddOutline,
  DownloadOutline,
  SearchOutline,
  EllipsisHorizontal,
  CloudUploadOutline,
  ArrowBackOutline
} from '@vicons/ionicons5'
import dayjs from 'dayjs'
import { projectService } from '../../services/project.service'
import { ProjectData } from '../../services/types'

// 分辨率转换工具函数
function resolutionToSize(resolution: string): { width: number; height: number } {
  switch (resolution) {
    case '720p':
      return { width: 1280, height: 720 }
    case '1080p':
      return { width: 1920, height: 1080 }
    case '4k':
      return { width: 3840, height: 2160 }
    case 'square':
      return { width: 1080, height: 1080 }
    case 'portrait':
      return { width: 1080, height: 1920 }
    default:
      return { width: 1280, height: 720 }
  }
}

const router = useRouter()
const message = useMessage()

// 标签页状态
const activeTab = ref('all')

// 搜索和排序
const searchText = ref('')
const sortBy = ref('updatedAt')
const sortOptions = [
  { label: '最近更新', value: 'updatedAt' },
  { label: '最早更新', value: 'updatedAt-asc' },
  { label: '名称 A-Z', value: 'name-asc' },
  { label: '名称 Z-A', value: 'name-desc' },
  { label: '创建时间', value: 'createdAt' }
]

// 默认缩略图
const defaultThumbnail = 'https://naive-ui.oss-cn-beijing.aliyuncs.com/carousel-img/carousel3.jpeg'

// 项目数据
const projects = ref<ProjectData[]>([])
const loading = ref(true)

// 模板数据
const templates = ref([
  {
    id: 't1',
    name: '传统皮影戏模板',
    description: '适合制作传统风格的皮影戏动画，包含经典场景和角色',
    category: '传统',
    thumbnail: 'https://naive-ui.oss-cn-beijing.aliyuncs.com/carousel-img/carousel4.jpeg'
  },
  {
    id: 't2',
    name: '现代动画模板',
    description: '现代风格的皮影动画模板，适合创作当代题材作品',
    category: '现代',
    thumbnail: 'https://naive-ui.oss-cn-beijing.aliyuncs.com/carousel-img/carousel1.jpeg'
  },
  {
    id: 't3',
    name: '儿童故事模板',
    description: '专为儿童故事设计的模板，色彩鲜艳，角色可爱',
    category: '儿童',
    thumbnail: 'https://naive-ui.oss-cn-beijing.aliyuncs.com/carousel-img/carousel2.jpeg'
  }
])

// 最近项目
const recentProjects = ref<ProjectData[]>([])

// 加载项目数据
async function loadProjects() {
  loading.value = true
  try {
    // 使用新的服务API
    const projectsResult = await projectService.getAllProjects()
    if (projectsResult.success && projectsResult.data) {
      projects.value = projectsResult.data
    } else {
      throw new Error(projectsResult.error?.message || '获取项目列表失败')
    }

    const recentResult = await projectService.getRecentProjects(5)
    if (recentResult.success && recentResult.data) {
      recentProjects.value = recentResult.data
    } else {
      console.warn('获取最近项目失败:', recentResult.error?.message)
      recentProjects.value = []
    }
  } catch (error) {
    console.error('加载项目失败:', error)
    message.error(error instanceof Error ? error.message : '加载项目失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadProjects()
})

// 筛选后的项目
const filteredProjects = computed(() => {
  let result = [...projects.value]
  
  // 搜索过滤
  if (searchText.value) {
    const searchLower = searchText.value.toLowerCase()
    result = result.filter(
      project => project.name.toLowerCase().includes(searchLower) || 
                (project.description && project.description.toLowerCase().includes(searchLower))
    )
  }
  
  // 排序
  switch (sortBy.value) {
    case 'updatedAt':
      result.sort((a, b) => {
        const dateA = a.updatedAt ? new Date(a.updatedAt).getTime() : 0
        const dateB = b.updatedAt ? new Date(b.updatedAt).getTime() : 0
        return dateB - dateA
      })
      break
    case 'updatedAt-asc':
      result.sort((a, b) => {
        const dateA = a.updatedAt ? new Date(a.updatedAt).getTime() : 0
        const dateB = b.updatedAt ? new Date(b.updatedAt).getTime() : 0
        return dateA - dateB
      })
      break
    case 'name-asc':
      result.sort((a, b) => a.name.localeCompare(b.name))
      break
    case 'name-desc':
      result.sort((a, b) => b.name.localeCompare(a.name))
      break
    case 'createdAt':
      result.sort((a, b) => {
        const dateA = a.createdAt ? new Date(a.createdAt).getTime() : 0
        const dateB = b.createdAt ? new Date(b.createdAt).getTime() : 0
        return dateB - dateA
      })
      break
  }
  
  return result
})

// 项目操作菜单
const projectActions = [
  {
    label: '打开',
    key: 'open'
  },
  {
    label: '重命名',
    key: 'rename'
  },
  {
    label: '复制',
    key: 'duplicate'
  },
  {
    label: '导出',
    key: 'export'
  },
  {
    type: 'divider',
    key: 'd1'
  },
  {
    label: '删除',
    key: 'delete'
  }
]

// 新建项目表单
const showNewProjectModal = ref(false)
const formRef = ref<FormInst | null>(null)
const newProjectForm = ref({
  name: '',
  description: '',
  resolution: '720p',
  frameRate: 30
})

// 表单验证规则
const formRules = {
  name: {
    required: true,
    message: '请输入项目名称',
    trigger: 'blur'
  }
}

// 分辨率选项
const resolutionOptions = [
  { label: '720p (1280x720)', value: '720p' },
  { label: '1080p (1920x1080)', value: '1080p' },
  { label: '4K (3840x2160)', value: '4k' },
  { label: '方形 (1080x1080)', value: 'square' },
  { label: '竖屏 (1080x1920)', value: 'portrait' }
]

// 帧率选项
const frameRateOptions = [
  { label: '24 FPS (电影)', value: 24 },
  { label: '30 FPS (标准)', value: 30 },
  { label: '60 FPS (高帧率)', value: 60 }
]

// 导入项目
const showImportModal = ref(false)

// 格式化日期
const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm')
}

// 格式化时长
const formatDuration = (ms) => {
  const seconds = Math.floor(ms / 1000)
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 打开项目
const openProject = async (project) => {
  try {
    const result = await projectService.updateProjectLastOpened(project.id)
    if (!result.success) {
      console.warn('更新最后打开时间失败:', result.error?.message)
    }
    router.push(`/workspace/editor?id=${project.id}`)
  } catch (error) {
    console.error('打开项目失败:', error)
    message.error('打开项目失败')
  }
}

// 处理项目操作
const handleProjectAction = async (key, project) => {
  switch (key) {
    case 'open':
      openProject(project)
      break
    case 'rename':
      // 实现重命名逻辑
      message.info(`重命名项目: ${project.name}`)
      break
    case 'duplicate':
      // 实现复制逻辑
      message.success(`已复制项目: ${project.name}`)
      break
    case 'export':
      router.push(`/export?id=${project.id}`)
      break
    case 'delete':
      try {
        const result = await projectService.deleteProject(project.id)
        if (result.success && result.data) {
          message.success(`已删除项目: ${project.name}`)
          loadProjects() // 重新加载项目列表
        } else {
          message.error(result.error?.message || '删除项目失败')
        }
      } catch (error) {
        console.error('删除项目失败:', error)
        message.error('删除项目失败')
      }
      break
  }
}

// 创建新项目
const createNewProject = () => {
  showNewProjectModal.value = true
}

// 处理创建项目
const handleCreateProject = () => {
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        // 转换分辨率
        const resolution = resolutionToSize(newProjectForm.value.resolution)

        // 创建项目
        const result = await projectService.createProject({
          name: newProjectForm.value.name,
          description: newProjectForm.value.description,
          resolution,
          frameRate: newProjectForm.value.frameRate
        })

        if (result.success && result.data) {
          message.success(`创建项目成功: ${result.data.name}`)

          // 重置表单
          newProjectForm.value = {
            name: '',
            description: '',
            resolution: '720p',
            frameRate: 30
          }

          // 关闭对话框
          showNewProjectModal.value = false

          // 重新加载项目列表
          await loadProjects()

          // 导航到编辑器
          router.push(`/workspace/editor?id=${result.data.id}`)
        } else {
          message.error(result.error?.message || '创建项目失败')
        }
      } catch (error) {
        console.error('创建项目失败:', error)
        message.error('创建项目失败')
      }
    }
  })
}

// 取消创建项目
const cancelCreateProject = () => {
  newProjectForm.value = {
    name: '',
    description: '',
    resolution: '720p',
    frameRate: 30
  }
  showNewProjectModal.value = false
}

// 导入项目
const importProject = () => {
  showImportModal.value = true
}

// 上传前处理
const beforeUpload = (data) => {
  // 实际项目中应该检查文件格式等
  message.info(`准备导入文件: ${data.file.name}`)
  return false // 阻止默认上传行为
}

// 处理导入项目
const handleImportProject = () => {
  message.success('项目导入成功')
  showImportModal.value = false
}

// 取消导入项目
const cancelImportProject = () => {
  showImportModal.value = false
}

// 使用模板
const useTemplate = (template) => {
  message.info(`使用模板: ${template.name}`)
  // 实际项目中应该基于模板创建新项目
  router.push('/workspace/editor')
}

// 返回上一页
const goBack = () => {
  router.push('/welcome')
}
</script>

<style lang="scss" scoped>
.project-list-container {
  padding: 20px;
  
  .header-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .left {
      display: flex;
      align-items: center;
      gap: 12px;
      
      h1 {
        margin: 0;
        font-size: 24px;
        font-weight: 500;
      }
    }
    
    .right {
      display: flex;
      gap: 12px;
    }
  }
  
  .custom-tabs {
    :deep(.n-tabs-nav) {
      background-color: var(--card-color);
      border-radius: 8px;
      padding: 0 16px;
      margin-bottom: 20px;
    }
    
    :deep(.n-tabs-tab) {
      padding: 12px 16px;
      font-size: 16px;
      transition: all 0.3s;
      
      &:hover {
        color: var(--primary-color);
      }
      
      &.n-tabs-tab--active {
        font-weight: 500;
      }
    }
    
    :deep(.n-tabs-tab-wrapper) {
      padding: 0 4px;
    }
    
    :deep(.n-tabs-bar) {
      height: 3px;
      border-radius: 3px;
    }
  }
  
  .filter-bar {
    margin-bottom: 20px;
    max-width: 500px;
  }
  
  .projects-grid,
  .templates-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
    
    .project-card,
    .template-card {
      transition: transform 0.2s, box-shadow 0.2s;
      border-radius: 8px;
      overflow: hidden;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
      }
      
      .project-thumbnail,
      .template-thumbnail {
        height: 160px;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: center;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .project-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .project-name {
          font-weight: 500;
          font-size: 16px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
      
      .project-info,
      .template-info {
        font-size: 14px;
        
        .info-row {
          display: flex;
          margin-bottom: 6px;
          
          .label {
            color: var(--text-color-secondary);
            width: 70px;
            flex-shrink: 0;
          }
          
          .value {
            flex-grow: 1;
          }
        }
        
        .template-description {
          margin-top: 8px;
          color: var(--text-color-secondary);
          font-size: 13px;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
      }
    }
  }
  
  .project-avatar {
    width: 60px;
    height: 60px;
    overflow: hidden;
    border-radius: 8px;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  .project-meta {
    display: flex;
    gap: 16px;
    font-size: 13px;
    color: var(--text-color-secondary);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .project-list-container {
    padding: 10px;
    
    .header-actions {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
      
      .right {
        width: 100%;
        justify-content: space-between;
      }
    }
    
    .projects-grid,
    .templates-grid {
      grid-template-columns: 1fr;
    }
  }
}
</style> 